package com.liang.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.nio.charset.StandardCharsets;

/**
 * Created with IntelliJ IDEA.
 * User: XIAOLIANG
 * Date: 2021/6/19
 * Time: 17:05
 * Description: 交换机的回调方法
 */
@Component
@Slf4j
public class MyCallBack implements RabbitTemplate.ConfirmCallback,RabbitTemplate.ReturnCallback {

    //注入
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @PostConstruct
   public void init(){
       rabbitTemplate.setConfirmCallback(this);
       rabbitTemplate.setReturnCallback(this);
   }

    //交换机确认回调的方法

    /**
     *
     * @param correlationData  保存回调消息的ID 及相关信息
     * @param ack 交换机是否收到消息
     * @param cause  失败的原因
     */

    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {

        String id  = correlationData.getId()!=null ?correlationData.getId():"";

        if (ack){

            log.info("交换机已经收到了消息 id:{}",id);

        }else {
            log.info("交换机未收到ID为:{}的消息,由于原因:{}",id,cause);
        }

    }


    //消息回退 回调的方法
    @Override
    public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {

        log.error("消息{},被交换机{},回退,回退原因:{},路由key:{}",new String(message.getBody(), StandardCharsets.UTF_8),exchange,replyCode+replyText,routingKey);


    }
}